Aula 3

Semabio 2024

Carolina Musso

IB/UnB

  • Estrutura:

    • Aula 1: Instalação e Intro Rmarkdown
    • Aula 2 (hoje): Rmarkdown, pacote dplyr
    • Aula 3: Gráficos ggplot, Tabelas resumo e testes estatísticos

Quiz

Revisando …

O Rmarkdown tem 3 partes

  • Cabeçalho: YAML

  • Texto: Markdown

  • Código: chunk e inline

Termos

  • Funções
  • Pacotes
  • Objetos
  • Variáveis

Gráficos

Leitura para aprofundamento

O poder da visualização

- DataViz, para os íntimos

  • Muito importante já na parte de exploração dos dados

    • Ajudam ao cérebro a dar sentido em todas aquelas informações

    • Ajuda a levantar hipóteses

  • Importante na apresentação final dos resultados

ggplot2

Mas onde está o carregamento desse pacote no nosso software?

  • Ele faz parte do tidyverse!

O que vamos (começar) aprender hoje

  • Uma forma mais rápida de visualizar (poucas linhas de código)

    • Sem (muitas) firulas visuais
  • Não vamos focar, no momento, em deixar os gráficos pefeitos.

  • Adivinhem: o ggplot faz as duas coisas!

A lógica do ggplot2

A lógica do ggplot

O “canvas” vazio

iris_media_area %>% 
  ggplot()

Os dados (eixos)

iris_media_area %>% 
  ggplot() +
  aes(x = Species, y = area_media)

A geometria

iris_media_area %>% 
  ggplot() +
  aes(x = Species, y = area_media)+
  geom_col()

iris_media_area %>% 
  ggplot(aes(x=Species, y=area_media)) +
  geom_col(fill="#9c9ff7",
           color="#684dcf")+
  geom_errorbar(aes(ymin = area_media-area_dp, 
                ymax = area_media+area_dp),
                width = 0.3,
                color = "#684dcf")+
  geom_text(aes(y = area_media+area_dp,
                label = round(area_media,1) ),
                hjust = -0.5)+
  theme_classic(base_size = 15)+
  labs(title = "Área média da Pétala ",
       subtitle = "Comparação entre espécies",
       caption = "Fonte: Dados iris",
       x = "",
      y = expression("Área média da pétala (cm"^2*")"))+
  coord_flip()+
  theme(axis.text.y = element_text(face = "italic"))

Lógica do ggplot

As camadas são adicionadas com um “+”

  • Diferença + para %>%
  • Há as partes estáticas e partes que dinâmicas (que respondem aos dados)
    • estão dentro do aes().
  • Cuidado com as aspas (principalmente nas opções de parâmetros)!
  • Conheça as variáveis (numéricas ou categóricas)
  • É preciso ter no mínimo a função ggplot() e uma função de geometria geom_?()
  • Há várias formas de escrever a mesma coisa!

Várias formas de escrever a mesma coisa

ggplot(data = iris) + 
  geom_point(mapping = aes(x = Petal.Length, y = Petal.Width))

ggplot(iris) + 
  geom_point(aes(x = Petal.Length, y = Petal.Width))

ggplot(iris, aes(x = Petal.Length, y = Petal.Width)) + 
  geom_point( )

ggplot(iris) + 
  aes(x = Petal.Length, y = Petal.Width) +
  geom_point()

Customizações

ggplot(iris) + 
  aes(x = Petal.Length, y = Petal.Width,
      shape=Species, color=Species) +
  geom_point()+
  scale_color_manual(values=c("aquamarine", 
                              "deeppink1",
                              "#684dcf"))+
  theme_classic()

Desafio (#Forms)

iris |> 
ggplot() +
  geom_boxplot(
    aes(x = Species,
        y = Petal.Width,
        fill=Species))

PRÁTICA

pacote ggstatsplot

Documentação

  • Vários parâmetros

Pacotes para tabelas

flextable

  • Ótimo para gerar os arquivos em word!
tab1 <- iris_media_area %>% 
flextable()

Lógica…

Gosto de pensar que também funciona como “camadas”.

  • alinhamento
  • fonte
  • largura
  • cores…

width : Largura

flextable( iris_media_area) %>% 
  width(width=3)

Species

area_media

area_dp

setosa

0.182800

0.09057729

versicolor

2.860200

0.68420143

virginica

4.963387

0.66677756

flextable(iris_media_area) %>% 
  width(width=1) %>% 
  width (j=1, width=2) 

Species

area_media

area_dp

setosa

0.182800

0.09057729

versicolor

2.860200

0.68420143

virginica

4.963387

0.66677756

bold: Negrito

  • podemos usar a mesma lógica para as colunas

  • Mas com o negrito, e outras formatações internas podemos também trabalhar nas linhas.

  • j eram as colunas …

  • i são as linhas

flextable(iris_media_area) %>% 
  width(width=1) %>% 
  width(j=1, width=3) %>% 
  bold(i=1)

Species

area_media

area_dp

setosa

0.182800

0.09057729

versicolor

2.860200

0.68420143

virginica

4.963387

0.66677756

flextable(iris_media_area) %>% 
  width(width=1) %>% 
  width(j=1, width=3) %>% 
  bold(part= "header")

Species

area_media

area_dp

setosa

0.182800

0.09057729

versicolor

2.860200

0.68420143

virginica

4.963387

0.66677756

alinhamento

flextable(iris_media_area) %>% 
  width(width=1) %>% 
  width (j=1, width=2) %>% 
  bold (part = "header") %>% 
  align(align="center", part="all") %>% 
  align(align="left", j=1,  part="all")

Species

area_media

area_dp

setosa

0.182800

0.09057729

versicolor

2.860200

0.68420143

virginica

4.963387

0.66677756

Mais firulas

flextable(iris_media_area) %>% 
  width(width=1) %>% 
  width (j=1, width=0.5) %>% 
  bold (part = "header") %>% 
  align(align="center", part="all") %>% 
  align(align="left", j=1,  part="all") %>% 
  vline(j=1, border=fp_border(color = "purple",
                              style = "dotted", 
                              width = 1) ) %>% 
  set_header_labels( 
  Species="Espécie") %>% 
  compose(
    i = 1, j = c(2,3), part = "header",
  value = c(as_paragraph(
    "Área Média / cm",
    as_sup("2")),
    as_paragraph(
    "Desvio Padrão / cm",
    as_sup("2"))
  )
) %>% 
  font(part = "all", fontname = "Verdana") %>% 
  bg(i =  ~ area_dp/area_media >= 0.45, bg="yellow") %>% 
  colformat_double(decimal.mark = ",",
                   big.mark = ".",
                   digits = 2) %>% 
  colformat_int(big.mark = ".")

Espécie

Área Média / cm2

Desvio Padrão / cm2

setosa

0,18

0,09

versicolor

2,86

0,68

virginica

4,96

0,67

gtsummary

gtsummary

iris_filt <- iris %>% 
  mutate(Species=as.character(Species)) %>% 
  filter(Species!="setosa") 
  
 iris_filt %>%  
  select(-Species) %>% 
  tbl_summary()
Characteristic N = 1001
Sepal.Length 6.30 (5.80, 6.70)
Sepal.Width 2.90 (2.70, 3.03)
Petal.Length 4.90 (4.38, 5.53)
Petal.Width 1.60 (1.30, 2.00)
1 Median (IQR)
iris_filt %>% 
  tbl_summary(by= Species)
Characteristic versicolor, N = 501 virginica, N = 501
Sepal.Length 5.90 (5.60, 6.30) 6.50 (6.23, 6.90)
Sepal.Width 2.80 (2.53, 3.00) 3.00 (2.80, 3.18)
Petal.Length 4.35 (4.00, 4.60) 5.55 (5.10, 5.88)
Petal.Width 1.30 (1.20, 1.50) 2.00 (1.80, 2.30)
1 Median (IQR)

gtsummary

iris_filt %>% 
  tbl_summary(by= Species, 
              statistic = list(all_continuous() ~ "{mean} ({sd})") )
Characteristic versicolor, N = 501 virginica, N = 501
Sepal.Length 5.94 (0.52) 6.59 (0.64)
Sepal.Width 2.77 (0.31) 2.97 (0.32)
Petal.Length 4.26 (0.47) 5.55 (0.55)
Petal.Width 1.33 (0.20) 2.03 (0.27)
1 Mean (SD)
iris_filt %>% 
  tbl_summary(by= Species, 
              statistic = list(
                all_continuous() ~ "{mean} ({sd})") ) %>% 
  add_p() %>% 
  bold_labels() %>% 
  italicize_levels() %>%  
  bold_p(t = 0.8)
Characteristic versicolor, N = 501 virginica, N = 501 p-value2
Sepal.Length 5.94 (0.52) 6.59 (0.64) <0.001
Sepal.Width 2.77 (0.31) 2.97 (0.32) 0.005
Petal.Length 4.26 (0.47) 5.55 (0.55) <0.001
Petal.Width 1.33 (0.20) 2.03 (0.27) <0.001
1 Mean (SD)
2 Wilcoxon rank sum test
iris_filt %>% 
  tbl_summary(by= Species, 
              statistic = list(
                all_continuous() ~ "{mean} ({sd})")) %>% 
  add_p(test= everything() ~"t.test") %>% 
  bold_labels() %>% 
  italicize_levels() %>%  
  bold_p(t = 0.8)
Characteristic versicolor, N = 501 virginica, N = 501 p-value2
Sepal.Length 5.94 (0.52) 6.59 (0.64) <0.001
Sepal.Width 2.77 (0.31) 2.97 (0.32) 0.002
Petal.Length 4.26 (0.47) 5.55 (0.55) <0.001
Petal.Width 1.33 (0.20) 2.03 (0.27) <0.001
1 Mean (SD)
2 Welch Two Sample t-test

Prática Tabelas

Obrigada!